package com.mg.framework.kernel;

import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;

public abstract class Screen {

	protected float x = 0;
	protected float y = 0;
	protected int width = 0;
	protected int height = 0;

	protected Bitmap frameBuffer = null;
	protected Canvas canvas = null;

	protected Map<String, Object> actors = null;

	public Screen(int width, int height) {
		this.width = width;
		this.height = height;

		this.frameBuffer = Bitmap.createBitmap(this.width, this.height,
				Config.ARGB_8888);

		this.canvas = new Canvas(this.frameBuffer);
		this.actors = new HashMap<String, Object>();
	}

	protected Object addActor(String actorName, Object actor) {
		this.actors.put(actorName, actor);
		return actor;
	}

	protected Object getActor(String actorName) {
		return this.actors.get(actorName);
	}
	
	protected BaseActor getBaseActor(String actorName) {
		return (BaseActor)this.actors.get(actorName);
	}

	public int getWidth() {
		return this.width;
	}

	public int getHeight() {
		return this.height;
	}

	public float getXCenter() {
		return this.width / 2;
	}

	public float getYCenter() {
		return this.height / 2;
	}

	void gUpdate() {
		this.gameUpdate();
	}

	protected void gameUpdate() {
	}

	protected void screenUpdate(Canvas canvas) {
	}

	void sUpdate(Canvas canvas) {
		this.canvas.drawColor(Color.BLACK);
		this.screenUpdate(this.canvas);
		canvas.drawBitmap(this.frameBuffer, this.x, this.y, null);
	}

	protected void dispense(MotionEvent event) {
		Object[] actors = this.actors.values().toArray();
		for (int i = 0; i < actors.length; i++) {
			if (Touchable.class.isInstance(actors[i])
					&& ((Touchable) actors[i]).isTouched(event)) {
				((Touchable) actors[i]).onTouchEvent(event);
			}
		}
	}

	protected void dispenseToActors(String[] actorsName, MotionEvent event) {
		BaseActor a = null;
		for (int i = 0; i < actorsName.length; i++) {
			a = (BaseActor)this.getActor(actorsName[i]);
			if (Touchable.class.isInstance(a)
					&& ((Touchable) a).isTouched(event)) {
				((Touchable) a).onTouchEvent(event);
			}
		}
	}
}